package com.zbs.framework.security.handler;

import com.zbs.framework.common.handler.FrameworkBusinessRuntimeException;
import com.zbs.framework.common.utils.ErrEnum;
import com.zbs.framework.common.utils.ResponseUtil;
import com.zbs.framework.common.utils.ResultUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Zbs
 * @createTime: 2021/2/25 11:51
 * 统一未授权处理
 */
@Component
public class UnAuthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if (e.getCause() instanceof FrameworkBusinessRuntimeException) {
            FrameworkBusinessRuntimeException exception =  (FrameworkBusinessRuntimeException) e.getCause();
            ResponseUtil.out(response, request, ResultUtil.error().code(exception.getErrCode()).message(exception.getMessage()));
        } else {
            ResponseUtil.out(response, request, ResultUtil.error(ErrEnum.UN_AUTHORIZED));
        }
    }
}
